package EventLoopTest.EventLoopTutorial;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.nio.charset.StandardCharsets;

/**
 * EventLoop 入门示例4：Boss和Worker的分工
 * 学习目标：理解BossGroup和WorkerGroup的职责
 */
public class Demo04_BossAndWorker {
    public static void main(String[] args) throws Exception {
        // Boss和Worker的餐厅比喻：
        // BossGroup = 迎宾（接待客人入座）
        // WorkerGroup = 服务员（为客人点餐、上菜）
        
        // 1. 创建两个EventLoopGroup
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);    // 只需1个线程接受连接
        EventLoopGroup workerGroup = new NioEventLoopGroup(4);  // 4个线程处理业务
        
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)  // 设置两个组
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            // 当客户端连接时会调用这个方法
                            // 此时已经由BossGroup接受了连接
                            // 现在要为这个连接配置WorkerGroup的处理器
                            
                            ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
                                    // 这个方法在WorkerGroup的EventLoop中执行
                                    String request = msg.toString(StandardCharsets.UTF_8);
                                    System.out.println("收到消息: " + request);
                                    System.out.println("处理线程: " + Thread.currentThread().getName());
                                    System.out.println("EventLoop: " + ctx.channel().eventLoop());
                                    
                                    // 响应客户端
                                    String response = "你好，我收到了: " + request;
                                    ctx.writeAndFlush(Unpooled.copiedBuffer(response, StandardCharsets.UTF_8));
                                }
                                
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) {
                                    System.out.println("\n=== 新客户端连接 ===");
                                    System.out.println("客户端地址: " + ctx.channel().remoteAddress());
                                    System.out.println("分配的WorkerEventLoop: " + ctx.channel().eventLoop());
                                }
                            });
                        }
                    });
            
            // 绑定端口
            ChannelFuture future = bootstrap.bind(9999).sync();
            System.out.println("=== 服务器启动成功 ===");
            System.out.println("监听端口: 9999");
            System.out.println("BossGroup线程数: 1");
            System.out.println("WorkerGroup线程数: 4");
            System.out.println("\n使用telnet测试: telnet localhost 9999");
            
            // 等待服务器关闭
            future.channel().closeFuture().sync();
            
        } finally {
            // 优雅关闭
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

